import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import util.FileUtil;

import java.io.File;
import java.io.IOException;

/**
 * @author <a href="mailto:HelloHeSir@gmail.com">HeC</a>
 * @date 2018/12/27 9:42
 * 将对应环境拷贝到main下
 */
@Mojo(name = "build")
public class BuildMojo extends AbstractMojo {

    public static final String MAIN_NAME = "main";

    /**
     * Maven Project. 使用插件的maven项目
     */
    @Parameter(property = "project", required = true, readonly = true)
    private MavenProject project;

    /**
     * 当前替换环境
     */
    @Parameter(property = "name", defaultValue = MAIN_NAME)
    private String name;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (MAIN_NAME.equals(name)) {
            getLog().info("current MAIN_NAME is null or MAIN_NAME is [" + MAIN_NAME + "]...............................");
            return;
        }
        getLog().info(String.format("========================building【%s】=============================", project.getName()));

        File projectFile = project.getBasedir();
        String itemPath = projectFile.getAbsolutePath() + "/src/" + name;
        String mainPath = projectFile.getAbsolutePath() + "/src/main";
        File itemFile = new File(itemPath);
        File mainFile = new File(mainPath);
        if (!itemFile.exists()) {
            getLog().info("directory is not exists:\n" + itemPath);
            return;
        }
        if (!mainFile.exists()) {
            getLog().info("directory is not exists:\n" + mainPath);
            return;
        }

        try {
            copyFiles(itemFile.getAbsolutePath(), mainFile.getAbsolutePath());
//            deleteOtherDirectory(projectFile);
            getLog().info(String.format("【%s】success............................", project.getName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除其余配置文件
     */
    private void deleteOtherDirectory(File projectFile) {
        File[] files = new File(projectFile.getAbsolutePath() + "/src").listFiles();
        for (File file : files) {
            if (!MAIN_NAME.equals(file.getName())) {
                FileUtil.delFolder(file.getAbsolutePath());
            }
        }
    }

    /**
     * 拷贝
     *
     * @param itemPath 需要拷贝的文件
     * @param copyPath 要拷贝到的路径
     */
    private void copyFiles(String itemPath, String copyPath) throws IOException {
        FileUtils.copyDirectory(new File(itemPath),new File(copyPath));
    }

}